package com.hisen.algorithm.sort;

import com.hisen.algorithm.sort.tools.ArrayTool;


public class BucketSort {

    /**
     * 对传入的整型数组进行桶排序
     *
     * @param order  默认正序“asc”，“desc”倒序
     * @param numArr 要排序的目标
     */
    public static int[] sort(String order, int[] numArr) {
        if (numArr == null || numArr.length <= 1) {
            return numArr;
        }
        int arrLength = numArr.length;
        int[] sorted = new int[arrLength];
        Integer minOfArr = ArrayTool.getMinOfArr(numArr);
        Integer maxOfArr = ArrayTool.getMaxOfArr(numArr);
        int size = maxOfArr - minOfArr + 1;
        int book[] = new int[size];
        for (int i : numArr) {//桶排序
            book[maxOfArr - i]++;//trueValue=maxOfArr-i
        }
        if (order.equals("desc")) {//倒序
            int index = 0;
            for (int i = 0; i < book.length; i++) {
                int trueVaule = maxOfArr - i;
                while (book[i] > 0) {
                    book[i]--;
                    sorted[index] = trueVaule;
                    index++;
                }
            }
        } else {
            for (int i = 0; i < book.length; i++) {//正序
                int trueValue = maxOfArr - i;
                while (book[i] > 0) {
                    book[i]--;
                    sorted[arrLength - 1] = trueValue;
                    arrLength--;
                }
            }
        }
        return sorted;
    }

}
